<?php

namespace app\controller;

use app\model\User;
use app\model\UserFish;
use app\service\UserFishService;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

//用户钓鱼控制器
class UserFishController extends Base
{

    /**
     * 获取用户钓鱼信息
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function index(): Response
    {
        $user = (new User())->find($this->user_id);
        return $this->success('ok', $user->toArray());
    }



    //获取鱼谱列表
    public function guide(): Response
    {
        try {
            $res = (new UserFishService())->get_fish_guide();
            return $this->json($res);
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        }

    }


    /**
     * 获取用户拥有的鱼列表
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function list(): Response
    {
        $user_fish = (new UserFish())->with('fish')->where('user_id', $this->user_id)->select();
        return $this->success('ok', $user_fish->toArray());
    }

    //抛竿

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function throwing_rod(): Response
    {
        $keep_time = $this->request->post('keep_time', '0');

        //判断保持的时长在哪个区间内
        foreach (FISH_KEEP_TIME_PROPERTY as $item) {
            $interval = $item['时间区间'];
            // 判断$keep_time是否在这个时间区间内
            $isInRange = array_filter([$keep_time], function ($n) use ($interval) {
                return $n >= $interval[0] && $n <= $interval[1];
            });
            if (!empty($isInRange)) {
                $probability = $item['中鱼概率'];
            }
        }


        if (empty($probability)) {
            //配置信息错误
            return $this->fail('配置信息错误');
        }

        //根据概率随机获取钓取的鱼
        $res = (new UserFishService())->get_random_fish($this->user_id, $probability);
        //判断是否成功
        if ($res['code'] == 0) {
            return $this->fail($res['msg']);
        }

        //返回鱼的信息
        return $this->json($res);

    }


}